//
//  NYSearchListViewController.m
//  NiuWaJiaoYu
//
//  Created by MinLison on 2018/1/9.
//  Copyright © 2018年 niuwaketang. All rights reserved.
//

#import "NYSearchListViewController.h"
#import "NYCourseViewController.h"
#import "NYRefreshFooter.h"

//view
#import "NYHomeEntryCell.h"

//request
#import "NYSearchRequest.h"

// 搜索历史存储路径
#define NYSEARCH_SEARCH_HISTORY_CACHE_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"NYSearchhistories.plist"]

@interface NYSearchListViewController () <UISearchBarDelegate, QMUITableViewDelegate>

@property (nonatomic, strong) QMUISearchBar *mySearchBar;
@property (nonatomic, strong) QMUIButton *cancelButton;

@property (nonatomic, strong) NYSearchRequest *request;

// 搜索历史
@property (nonatomic, strong) NSMutableArray *searchMutaHistories;

// 搜索历史缓存保存路径
@property (nonatomic, copy) NSString *searchHistoriesCachePath;
// 搜索历史记录缓存数量，默认为20
@property (nonatomic, assign) NSUInteger searchHistoriesCount;

@end

@implementation NYSearchListViewController

#pragma mark - Life Cycle Methods

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
}
#pragma mark - Intial Methods
- (void)initUI {
    
    [self loadData];
    
    self.searchHistoriesCount = 20;
}
- (void)configNimbus {
    [super configNimbus];
    
    self.tableViewModel.delegate = self;
    @weakify(self);
    [self.tableViewActions attachToClass:[NYHomeEntryModel class] tapBlock:^BOOL(NYHomeEntryModel *object, id target, NSIndexPath *indexPath) {
        
        @strongify(self);
        [self.navigationController pushViewController:[[NYCourseViewController alloc] initWithDetailContentStatus:NYExamineRequestStatusChoose withId:[NSString stringWithFormat:@"%ld",object.id]] animated:true];
        return true;
    }];

}
- (void)initTableView {
    [super initTableView];
    
}

#pragma mark - Network Methods
- (void)loadData {
    
    [self configNimbus];
    [self setLoading:YES animation:YES];

    self.request = nil;
    [self.tableViewModel removeAll];
    [self.request clearCache];

    @weakify(self);
    [self.request startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYHomeEntryModel * _Nonnull data) {
        
        @strongify(self);
        NSArray *arrayM = data.list;
        if ([arrayM count] == 0) {
            [NYTipClass showText:@"暂无相关内容"];
            [self.navigationController popViewControllerAnimated:true];
        } else {
            [self.tableViewModel addObjectsFromArray:arrayM];
            [self.tableView reloadData];
            [self setSuccess];
        }
    } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
        [self setError:error];
    }];
}
- (void)setSuccess {
    [super setSuccess];
    [self configRefreshFooter];
}
- (void)configRefreshFooter {
    
    @weakify(self);
    self.tableView.mj_footer = [NYRefreshFooter footerWithRefreshingBlock:^{
        
        @strongify(self);
        [[self.request pullUp] startWithSuccess:^(__kindof BaseRequest * _Nonnull request, __kindof NYHomeEntryModel * _Nonnull data) {
            
            @strongify(self);
            NSArray *arrayM = data.list;
            [self.tableViewModel addObjectsFromArray:arrayM];
            [self.tableView reloadData];
            [self setSuccess];
            [arrayM count] == 0 ? [self.tableView.mj_footer endRefreshingWithNoMoreData] : [self.tableView.mj_footer endRefreshing];
        } failed:^(__kindof BaseRequest * _Nonnull request, NSError * _Nonnull error) {
            
            @strongify(self);
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }];
    }];

}
#pragma mark - Target Methods
- (void)popViewControllerAction {
    
    [self.navigationController popViewControllerAnimated:true];
}

#pragma mark - Public Methods

#pragma mark - Private Method
- (void)configNavigationBar:(BaseNavigationBar *)navigationBar {
    
    [self.navigationItem setLeftBarButtonItem:nil];
    self.navigationItem.hidesBackButton = true;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 65, 28)];
    view.backgroundColor = [UIColor whiteColor];
    view.layer.cornerRadius = 14.f;
    view.clipsToBounds = true;
    [view addSubview:self.mySearchBar];
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:self.cancelButton]];
    self.navigationItem.titleView = view;
    
    self.mySearchBar.text = self.searchString;
}
- (UIImage *)navigationBarShadowImage {
    return [[UIImage nav_bar_shadows] qmui_imageWithAlpha:0.8];
}
+ (NYViewControllerNavigationBarType)navigationBarType {
    
    return NYViewControllerNavigationBarTypeBlue;
}
#pragma mark - External Delegate
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 滚动时，回收键盘
    [self.mySearchBar resignFirstResponder];
}
//#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    if (searchBar.text.length == 0) return;
    
    [self saveSearchCacheAndRefreshView];

    self.searchString = searchBar.text;
    [self loadData];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    
}
/** 进入搜索状态调用此方法 */
- (void)saveSearchCacheAndRefreshView {
    
    QMUISearchBar *searchBar = self.mySearchBar;
    // 回收键盘
    [searchBar resignFirstResponder];
    // 先移除再刷新
    [self.searchMutaHistories removeObject:searchBar.text];
    [self.searchMutaHistories insertObject:searchBar.text atIndex:0];
    
    // 移除多余的缓存
    if (self.searchMutaHistories.count > self.searchHistoriesCount) {
        // 移除最后一条缓存
        [self.searchMutaHistories removeLastObject];
    }
    // 保存搜索信息
    [NSKeyedArchiver archiveRootObject:self.searchMutaHistories toFile:self.searchHistoriesCachePath];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

#pragma mark - Setter Getter Methods
- (NYSearchRequest *)request {
    if (!_request) {
        _request = [NYSearchRequest requestWithParams:@{@"keywords":self.searchString, kRequestKeyChannel:@(NYUserManager.channelID)}];
    }
    return _request;
}
- (QMUISearchBar *)mySearchBar {
    if (!_mySearchBar) {
        _mySearchBar = [[QMUISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH - 65, 28)];
        _mySearchBar.qmui_placeholderColor    = UIColorMakeWithHex(@"#D0D0D0");
        _mySearchBar.qmui_textColor           = UIColorMakeWithHex(@"#333333");
        _mySearchBar.qmui_textField.backgroundColor    = UIColorMakeWithHex(@"#FFFFFF");
        _mySearchBar.qmui_textField.returnKeyType = UIReturnKeySearch;//变为搜索按钮
        _mySearchBar.placeholder = @"输入课程名称";
        _mySearchBar.delegate = self;
        //        _mySearchBar.clipsToBounds = YES;
        //        _mySearchBar.layer.cornerRadius = 14.0f;
        _mySearchBar.qmui_textField.backgroundColor    = UIColorMakeWithHex(@"#FFFFFF");
        _mySearchBar.qmui_textField.tintColor = UIColorMakeWithHex(@"#5396FF");
    }
    return _mySearchBar;
}
- (QMUIButton *)cancelButton {
    if (!_cancelButton) {
        _cancelButton = [[QMUIButton alloc] qmui_initWithImage:nil title:@"取消"];
        _cancelButton.frame = CGRectMake(0, 0, 40, 40);
        [_cancelButton setTitleColor:[UIColor whiteColor] forState:0];
        _cancelButton.titleLabel.font = UIFontMake(14);
        [_cancelButton addTarget:self action:@selector(popViewControllerAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}
- (NSMutableArray *)searchMutaHistories {
    
    if (!_searchMutaHistories) {
        self.searchHistoriesCachePath = NYSEARCH_SEARCH_HISTORY_CACHE_PATH;
        _searchMutaHistories = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoriesCachePath]];
    }
    return _searchMutaHistories;
}
- (void)setSearchHistoriesCachePath:(NSString *)searchHistoriesCachePath {
    
    _searchHistoriesCachePath = [searchHistoriesCachePath copy];
    // 刷新
    self.searchMutaHistories = nil;
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
